package views

import (
	"errors"
	"go_web/common"
	"go_web/service"
	"log"
	"net/http"
	"strconv"
	"strings"
)

func (h *HTMLApi) Category(w http.ResponseWriter, r *http.Request) {
	//获取页面
	categoryTemplate := common.Template.Category

	//http://localhost:8080/c/1
	path := r.URL.Path
	CIdStr := strings.TrimPrefix(path, "/c/")
	CId, err := strconv.Atoi(CIdStr)
	if err != nil {
		categoryTemplate.WriteError(w, errors.New("路径不匹配"))
		return
	}

	if err := r.ParseForm(); err != nil {
		log.Println("ParseForm err")
		categoryTemplate.WriteError(w, errors.New("系统出错 ParseForm "))
		return
	}

	//获取page
	pageStr := r.Form.Get("page")

	page := 1

	if pageStr == "" {
		pageStr = "1"
	}
	page, _ = strconv.Atoi(pageStr)
	//获取每页显示数量
	pageSize := 5

	categoryResponse, err := service.GetPostsByCategoryID(CId, page, pageSize)
	if err != nil {
		categoryTemplate.WriteError(w, errors.New("categoryResponse err"))
		return
	}
	categoryTemplate.WriteData(w, categoryResponse)

}
